#include<cstdio>
#include<iostream>
#include<stack>
using namespace std;
struct point
{
	int x;
	int y;
};
bool is_come[1000][1000];
struct node
{
	struct point data;
	struct node *link;
};
void regionGrowing_raw(unsigned char *buf, int m, int n, int seed_y, int seed_x, int thresh, unsigned char *bufOut)
{
	stack<pair<int ,int>>s;
	int dx[8]={-1,0,1,-1,1,-1,0,1};
	int dy[8]= {-1,-1,-1,0,0,1,1,1};
	s.push(make_pair(seed_x,seed_y));
	memset(is_come,0,sizeof(is_come));
	is_come[seed_y][seed_x]=true;
	while(!s.empty())
	{
		int x=s.top().first;
		int y=s.top().second;
		s.pop();
		unsigned char temp=buf[y*n+x];
		for(int k=0;k<8;k++)
		{
			int nextx=x+dx[k];
			int nexty=y+dy[k];
			if(nextx<0||nextx>=n||nexty<0||nexty>=m)continue;
			if(is_come[nexty][nextx])continue;
			if(fabs((int)temp-(int)buf[nexty*n+nextx])<=thresh)
			{
				bufOut[nexty*n+nextx]=0;
				s.push(make_pair(nextx,nexty));
				is_come[nexty][nextx]=true;
			}
			else{
				bufOut[nexty*n+nextx]=255;
				s.push(make_pair(nextx,nexty));
				is_come[nexty][nextx]=true;
			}
		}

	}
}

int main()
{
	int m, n, seedx, seedy, thresh;
	FILE *fp;
	fp=fopen("/Users/yuzhengze/Documents/C++/数据结构/实验2/实验数据/5.raw", "rb");//路径要修改成自己电脑的路径
	m=350, n=500, seedy=187, seedx=258, thresh=50;// �ļ�4.raw

	unsigned char *buf = new unsigned char[m * n];
	fread(buf, sizeof(unsigned char), m*n, fp);
	fclose(fp);
	
	unsigned char *bufOut = new unsigned char[m * n];
	regionGrowing_raw(buf, m, n, seedy, seedx,  thresh, bufOut);//
	fp=fopen("/Users/yuzhengze/Documents/C++/数据结构/实验2/实验数据/5_out.raw","wb");//新建输出文件要跟读入文件不重名
	fwrite(bufOut, sizeof(unsigned char), m * n, fp);
	fclose(fp);
	delete []buf;
	delete []bufOut;

	int t;
	scanf("%d", &t);
}